package sk.isomi.minihr.mngts;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;

import sk.isomi.helpers.DateHelper;
import sk.isomi.minihr.entities.Employee;
import sk.isomi.minihr.entities.Manager;
import sk.isomi.minihr.entities.Project;

public class ProjectMngt {
	private ArrayList<Project> projects;
	
	public ProjectMngt() {
		projects = new ArrayList<Project>();
	}
	
	public boolean addProject(Project project) {
		return projects.add(project);
	}
	
	public boolean removeProject(Project project) {
		return projects.remove(project);
	}
	
	public boolean removeProject(Integer id) {
		Project project = findById(id);
		if (project != null) {
			return removeProject(project);
		}
		return false;
	}


	public Project findById(Integer id) {
		for (Project project : projects) {
			if (project.getId().equals(id)) {
				return project;
			}
		}
		return null;
	}
	
	public ArrayList<Project> getProjects() {
		return projects;
	}
	
	public boolean addManager(Project project, Manager manager) {
		if (project != null) {
			project.setManager(manager);
			return true;
		}
		return false;	
	}	

	public boolean addEmployee(Project project, Employee employee) {
		if (project != null) {			
			return project.getWorkers().add(employee);
		}
		return false;	
	}	

	public ArrayList<Project> findProjectByManager(Manager manager) {
		ArrayList<Project> found = new ArrayList<Project>();
		
		for (Project project : projects) {
			if (manager.getId().equals(project.getManager().getId())) {
				found.add(project);
			}
		}
		return found;
	}

	public ArrayList<Project> findProjectByWorker(Employee employee) {
		ArrayList<Project> found = new ArrayList<Project>();
		
		for (Project project : projects) {
			for (Employee worker : project.getWorkers()) {
				if (employee.getId().equals(worker.getId())) {
					found.add(project);
					break;
				}
				
			}
		}
		return found;
	}

	public int getCountRunningProjects(Date date) {
		int counter = 0;
		for (Project project : projects) {
			if (date.before(project.getEndDate())) {
				counter++;
			}
		}
		return counter;
	}

	public void printProjectProgressStatus(PrintStream printStream) {
		Date today = new Date();
		printStream.printf("Today is: %s\n", DateHelper.formatDate(today, "dd.MM.yy"));
		printStream.println("ProjectName|StartDate|FinishDate|Done");
		for (Project project : projects) {		
			double done = DateHelper.diffDateDays(project.getStartDate(), new Date()); 
			printStream.println(String.format("%s|%s|%s|%.0f%%\n", project.getName(), project.getStartDate(), project.getEndDate(), ((done / project.getLength()) * 100)));
		}
	}
	
	@Override
	public String toString() {
		return String.format("ProjectMngt [projects count=%d]", projects.size());
	}
}
